/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 * */

// AmzServer - Tototoy's server model.
// Author: tonyjobmails@gmail.com (tonyhack).
//
// Define class Epoller.
//
// Epoller is a simple wapper of epoll.
//

#include "epoller.h"
#include "logging.h"

namespace amz {

Epoller::Epoller(int size) {
  this->epoll_fd_ = epoll_create(size);
  if(this->epoll_fd_ == -1) {
    LOG(ERROR) << "Failed to create epoll fd.";
  }
}

Epoller::~Epoller() {
  this->Close();
}

bool Epoller::Register(int fd, int events, void *ptr) {
  struct epoll_event ev;
  ev.data.ptr = ptr;
  ev.data.fd = fd;
  ev.events = events;
  return 0 == epoll_ctl(this->epoll_fd_, EPOLL_CTL_ADD, fd, &ev);
}

bool Epoller::Unregister(int fd) {
  struct epoll_event ev;
  ev.data.fd = fd;
  return 0 == epoll_ctl(this->epoll_fd_, EPOLL_CTL_DEL, fd, &ev);
}

bool Epoller::Modify(int fd, int events, void *ptr) {
  struct epoll_event ev;
  ev.data.ptr = ptr;
  ev.data.fd = fd;
  ev.events = events;
  return 0 == epoll_ctl(this->epoll_fd_, EPOLL_CTL_MOD, fd, &ev);
}

int Epoller::Core(struct epoll_event *events, int max_events, int timeout_milliseconds = -1) {
  return epoll_wait(this->epoll_fd_, events, max_events, timeout_milliseconds);
}

void Epoller::Close() {
  if(this->epoll_fd >= 0) {
    if(close(this->epoll_fd) == 0) {
      this->epoll_fd = -1;
    } else {
      LOG(ERROR) << "Failed to close epoll fd.";
    }
  }
}

}  // namespace amz
#endif  // __SERIAL__NUMBER__POOL__H

